/**
 * 根据url的参数获取对应的值
 * @param url
 * @param variable
 * @returns string
 */
export function getQueryVariable(url: string, variable: string) {
  const query = url.split('?')
  let param = ''
  if (query.length > 1)
    param = query[1]

  const vars = param.split('&')
  for (const var_ of vars) {
    const pair = var_.split('=')
    if (pair[0].toLowerCase() == variable.toLowerCase()) {
      let value = pair[1]
      if (pair[1].includes('#/'))
        value = pair[1].split('#/')[0]
      else if (pair[1].includes('/'))
        value = pair[1].split('/')[0]

      return value
    }
  }
  return ''
}

/**
 * 对象转url query 字符串 name=John&age=30&city=New%20York
 * @example
```
const myObject = {
  name: 'John',
  age: 30,
  city: 'New York'
};
const queryString = objectToQueryString(myObject);
console.log(queryString);
输出结果：
name=John&age=30&city=New%20York
```
 */
export function objectToQueryString(obj: Record<string, any>) {
  const keyValuePairs: string[] = []
  for (const key in obj) {
    const value = obj[key]
    const encodedKey = encodeURIComponent(key)
    const encodedValue = encodeURIComponent(value)
    keyValuePairs.push(`${encodedKey}=${encodedValue}`)
  }

  return keyValuePairs.join('&')
}
